from functools import wraps
from sanic.request import Request
from sanic.response import text, HTTPResponse

from cookie import COOKIE_KEY
from my_logging import GetLogger

from .dict_checker import CheckDict

logger = GetLogger('RequestCheckingWrapper')


def CheckCookie(response_on_not_pass : HTTPResponse = text('Who the hell are you?', status = 403)):
    def my_decorator(func):
        @wraps(func)
        def check(request : Request):
            cookie_in_request = request.cookies.get(COOKIE_KEY)
            if cookie_in_request is None:
                return response_on_not_pass

            return func(request)
        return check
    return my_decorator


def CheckJson(
    checking_dict : dict,
    response_on_not_pass : HTTPResponse = text('I got rubbish.', status = 400)
):
    def my_decorator(func):
        @wraps(func)
        def check(request : Request):
            logger.debug(f'request.json = {request.json}')

            if not CheckDict(request.json, checking_dict):
                logger.info('request not pass the dict check.')
                return response_on_not_pass

            return func(request)
        return check
    return my_decorator


def CheckArgument(
    argument_names : tuple[str] | str,
    response_on_not_pass : HTTPResponse = text('I got rubbish.', status = 400)
):
    def my_decorator(func):
        @wraps(func)
        def check(request : Request):
            args = request.get_args()
            if isinstance(argument_names, tuple):
                for argument_name in argument_names:
                    if argument_name not in args:
                        logger.debug(f'request lack of argument [{argument_name}].')
                        return response_on_not_pass
            elif isinstance(argument_names, str):
                if argument_names not in args:
                    logger.debug(f'request lack of argument [{argument_names}].')
                    return response_on_not_pass

            return func(request)
        return check
    return my_decorator